//app.js
var httpUtil = require('utils/httpUtils');
const upload = require('/utils/uploadAndDown.js');
const Promise = require('/utils/promise.js').Promise;
const constant = require('/utils/constant.js');
const wsUtil = require('/utils/wsUtils.js');
const utilService = require('/utils/utilService.js');


App({
  onLaunch: function (options) {
    var self = this;
    if (options.scene == 1044) {
      console.log("&&&&&" + options.shareTicket)
      wx.getShareInfo({
        shareTicket: options.shareTicket,
        complete(res) {
          console.log(res)
        }
      })
    }
    console.log('options~: ' + options.query + "--------" + options);
    var inviteUserId = options.query.userId == undefined ? options.query.uId : options.query.userId;
    if (inviteUserId == undefined){
      inviteUserId = ""
    }
    self.globalData.inviteUserId = inviteUserId
    self.loginService()
    wx.hideTabBar()
  },
  onShow: function (options) {
  },
  requestService: function (success) {
    wx.request({
      url: 'https://quxian.zuanliantech.com/api_url/config.json',
      success: function (res) {
        success(res.data)
        console.log(res.data)
      }
    })
  },
  loginService: function(success){
    var self = this;
    // 检查是否授权
    this.loginPromise = Promise((resolve, reject) => {
      this.requestService(function (res) {
        // 如需改测试环境屏蔽下面两行, 正式环境放开注释
        // self.globalData.baseUrl = res.request;
        // self.globalData.sourceUrl = res.resource.substring(8, res.resource.length);
        wx.getSetting({
          success: (authRes) => {
            //判断用户是否授权
            if (authRes.authSetting['scope.userInfo']) {
              console.log('已经授权', authRes)
              // 已经授权，本地获取头像昵称
              Promise(self.login).then(loginRes => {
                console.log('微信登录成功')
                //发起网络请求
                console.log('发起登陆请求  ' + loginRes)
                httpUtil.http({
                  url: self.api.getToken,
                  method: "POST",
                  data: loginRes
                }).then(body => {
                  console.log('登录服务器成功  ' + body)
                  if (body.userId) {
                    self.globalData.userId = body.userId;
                  }
                  if (body.token) {
                    self.globalData.token = body.token;
                  } 
                  if (body.accessToken) {
                    self.globalData.accessToken = body.accessToken;
                  }
                  
                  resolve(body);
                  return body;
                });
                return loginRes;
              });
            } else {
              reject();
              console.log('未授权', authRes)
            }
          },
          fail: function () {
            reject();
          }
        })
      })
    });
  },
  login(resolve, reject) {
    var self = this;
    wx.login({
      success: function (res) {
        wx.getUserInfo({
          lang:"zh_CN",
          success: function (userInfoRes) {
            console.log('用户信息 ', userInfoRes.userInfo);
            self.globalData.userInfo = userInfoRes.userInfo;
            let param = {
              "encryptedData": userInfoRes.encryptedData,
              "iv": userInfoRes.iv,
              "inviteUserId": self.globalData.inviteUserId,
              'code': res.code,
              "nickName": userInfoRes.userInfo.nickName,
              "avatarUrl": userInfoRes.userInfo.avatarUrl,
              "country": userInfoRes.userInfo.country,
              "province": userInfoRes.userInfo.province,
              "city": userInfoRes.userInfo.city,
            }
            resolve(param);
          }, fail: function (err) {
            console.log('获取用户信息失败');
          }
        })
      },
      fail: function(err) {
        reject(err);
      }
    });
  },
  //这个方法中添加全局函数和数据
  globalData: {
    token: "", 
    accessToken:"",
    userInfo: null,
    sessionKey: null,
    testApp:'000',
    func: null,
    userId:"",
    sessionKey: null,
    inviteUserId:"",
    usedGoods:0,//用户可以购买的商品数
    userSweets:0,//用户拥有的果冻
    baseUrl: 'https://card-87.zuanliantech.com',
    sourceUrl: "resources",
    // baseUrl: 'https://api.quxianba.com',
    // sourceUrl: "resources"
  },
  func: {
    Get: httpUtil.Get,
    Post: httpUtil.Post,
    Delete: httpUtil.Delete,
    Upload: upload.uploadMultFiles,
    UploadFile: upload.uploadFiles
  },

  saveUserFormId: function(id,formType){
    httpUtil.Post(false, httpUtil.api.saveUserFormId,
      { "formId": id, "type": formType })
  },
  constant: constant,
  utilService: utilService,
  api: httpUtil.api,
  loginPromise: {},
  tokenPromise: {}
})
